package com.web.servlet.gameweb;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.google.gson.JsonObject;
import com.web.servlet.bean.Player;
import com.web.servlet.bean.RedisKey;
import com.web.servlet.bean.UserInfo;
import com.web.servlet.dao.DBConnect;
import com.web.servlet.manager.DaoManager;
import com.web.servlet.manager.RedisManager;
/**
 * 加入房间
 * @author davie.yu
 *
 */
public class JoinRoomServlet extends HttpServlet {

	private static final long serialVersionUID = 965679984515166855L;

	public JoinRoomServlet() {
		super();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String uid =request.getParameter("uid");//用户ID
		String gid =request.getParameter("gid");//游戏ID
		String rid =request.getParameter("rid");//房间号
		
		JsonObject o = new JsonObject();
		o.addProperty("cmd", "joinroomservlet");
		o.addProperty("uid", uid);
		o.addProperty("rid", rid);
		String re = HttpUtils.sentPost("http://112.74.133.57:2221/createroom/p", o.toString());
		
		
		
		 boolean result = true;
		 if(result) {	
				//RedisManager.getRedis().set(RedisKey.USERINFO + userInfo.getUser_id(), userInfo.pack());
			 Map<String,String> resMap = JSONObject.fromObject(re);
			 Document document = DocumentHelper.createDocument();
				Element rootElement = document.addElement("user");
				rootElement.addAttribute("st", resMap.get("result"));
				rootElement.addAttribute("to","token");// token
				rootElement.addAttribute("rid", resMap.get("rid"));// 房间号
				rootElement.addAttribute("ip", resMap.get("ip"));// 创建的游戏IP(Socket)
				rootElement.addAttribute("port", resMap.get("port"));// 创建的游戏端口
				rootElement.addAttribute("tid", resMap.get("tid"));// 创建游戏桌子号

				out.print(document.asXML());
		    }else{
	    		loginFail(out);
	    	}
		 out.flush();
		out.close();
	    
		
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}
	

	
	
	private void loginFail(PrintWriter out)
	{
		Document document = DocumentHelper.createDocument();
    	Element rootElement = document.addElement("user");
    	rootElement.addAttribute("st", "false");
    	rootElement.addAttribute("dc", "用户名或者密码不对");
    	out.print(document.asXML());
		
	}

}
